package com.qk.manangement.aspect;



import com.qk.common.properties.RedisProperties;
import com.qk.manangement.annotation.ClearRedisCache;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Set;

@Aspect
@Component
@Slf4j
public class RedisCacheClearAspect {
    
    private static final Logger logger = LoggerFactory.getLogger(RedisCacheClearAspect.class);
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    /**
     * 在被@ClearRedisCache注解标记的方法成功执行后执行
     */
    @AfterReturning(pointcut = "@annotation(com.qk.manangement.annotation.ClearRedisCache)")
    public void clearRedisCache(JoinPoint joinPoint) {
        try {
            // 获取方法签名
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            
            // 获取注解
            ClearRedisCache clearRedisCache = method.getAnnotation(ClearRedisCache.class);
            
            // 获取注解参数
            String keyPrefix = clearRedisCache.keyPrefix();
            String[] keys = clearRedisCache.keys();
            
            // 如果指定了具体的keys，则删除这些keys
            if (keys != null && keys.length > 0) {
                for (String key : keys) {
                    redisTemplate.delete(key);
                    log.info("已删除Redis缓存key: {}", key);
                }
            } else {
                // 如果没有指定具体keys，则根据前缀删除
                String prefix = keyPrefix;
                if (prefix == null || prefix.isEmpty()) {
                    prefix = RedisProperties.REDIS_KEY_PREFIX;
                }
                
                // 查找所有匹配前缀的key并删除
                Set<String> keysToDelete = redisTemplate.keys(prefix + "*");
                if (keysToDelete != null && !keysToDelete.isEmpty()) {
                    redisTemplate.delete(keysToDelete);
                    log.info("已删除{}个匹配前缀{}的Redis缓存", keysToDelete.size(), prefix);
                }
            }
        } catch (Exception e) {
            logger.error("清空Redis缓存时发生异常", e);
        }
    }
}
